import Cookies from 'js-cookie';
import api from '@/store/api';
import router from '@/router';

export const useAuthenticationStore = defineStore('authentication', () => {
  const authError = ref(false);
  const xsrfCookie = ref(Cookies.get('XSRF-TOKEN'));
  const isAuthenticatedCookie = ref(Cookies.get('IsAuthenticated'));
  const isLoggedIn = computed(
    () =>
      xsrfCookie.value !== undefined || isAuthenticatedCookie.value == 'true',
  );
  const token = computed(() => xsrfCookie.value);

  const authSuccess = async () => {
    const { initWebSocket } = await import('@/store/Plugins/WebSocketPlugin');
    initWebSocket();
    authError.value = false;
    xsrfCookie.value = Cookies.get('XSRF-TOKEN');
  };
  const login = function ({
    username,
    password,
  }: {
    username: string;
    password: string;
  }) {
    authError.value = false;
    return api
      .post('/login', { data: [username, password] }, undefined)
      .then(() => {
        authSuccess();
      })
      .catch((error) => {
        authError.value = true;
        throw new Error(error);
      });
  };
  const logoutReset = () => {
    Cookies.remove('XSRF-TOKEN');
    Cookies.remove('IsAuthenticated');
    localStorage.removeItem('storedUsername');
    xsrfCookie.value = undefined;
    isAuthenticatedCookie.value = undefined;
  };
  const logout = function () {
    api
      .post('/logout', { data: [] }, undefined)
      .then(() => {
        logoutReset();
      })
      .then(() => router.push('/login' as any))
      .catch((error) => console.log(error));
  };
  const getUserInfo = function (username: string) {
    return api
      .get(`/redfish/v1/AccountService/Accounts/${username}`)
      .then(({ data }) => data)
      .catch((error) => {
        console.log(error);
        throw error;
      });
  };
  const checkPasswordChangeRequired = async function (username: any) {
    return await api
      .get(`/redfish/v1/AccountService/Accounts/${username}`)
      .then(({ data: { PasswordChangeRequired } }) => PasswordChangeRequired)
      .catch((error) => console.log(error));
  };
  const resetStoreState = function () {
    authError.value = false;
    xsrfCookie.value = Cookies.get('XSRF-TOKEN');
    isAuthenticatedCookie.value = Cookies.get('IsAuthenticated');
  };

  return {
    authError,
    xsrfCookie,
    isAuthenticatedCookie,
    isLoggedIn,
    token,
    authSuccess,
    login,
    logoutReset,
    logout,
    getUserInfo,
    checkPasswordChangeRequired,
    resetStoreState,
  };
});
